package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.CommentDao;
import com.pojo.CommentPojo;
import com.util.Log;

@WebServlet(urlPatterns={"/user/SubmitComment"})
public class SubmitComment extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		
		String caseIdString = request.getParameter("caseId");
		String guestName = request.getParameter("guestName");
		String guestPhone = request.getParameter("guestPhone");
		String content = request.getParameter("content");
		System.out.println("Run Save Comments");
		
		// 获取IP
	    String clientIp = InetAddress.getLocalHost().getHostAddress();

	    
		CommentDao dao = new CommentDao();
		String message = "";
		if (caseIdString == null || "".equals(caseIdString)) {
			message = "配置案例ID，";
		} else if (guestName == null || "".equals(guestName)) {
			message += "输入姓名，";
		} else if (guestPhone == null || "".equals(guestPhone)) {
			message += "输入电话，";
		} else if (content == null || "".equals(content)) {
			message += "输入留言内容，";
		} else if(clientIp == null || "".equals(clientIp)) {
			message += "获取IP失败。";
		} else {
			int caseId = Integer.parseInt(caseIdString);
			Timestamp commentDate = new java.sql.Timestamp(new java.util.Date().getTime());
			CommentPojo pojo = new CommentPojo(caseId, guestName, guestPhone, commentDate, content);
			pojo.setGuestIp(clientIp);
			pojo.setVerifyResult(0);
			if (dao.addComment(pojo) > 0)
				message = "留言成功";
		}
		
        response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String json = "{\"status\":\""+message+"\"}";
		Log.write(json);
		out.println(json);
		out.flush();
        out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
